//
//  AppDelegate.m
//  TruckUser
//
//  Created by Ting Han on 2017/9/25.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "HTLoginVC.h"
#import "BaseNavigationController.h"
//高德地图
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
//友盟统计
#import "UMMobClick/MobClick.h"
#import "HTNotificationResultModel.h"
//友盟推送
#import "UMessage.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
#import <UserNotifications/UserNotifications.h>
#endif


@interface AppDelegate ()<
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
UNUserNotificationCenterDelegate
#endif
>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self newVersion];
    [self configUmClik];
    [self configUmPush:launchOptions];
    //高德地图
    [AMapServices sharedServices].apiKey = kAmapKey;
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    if ([HTMUserDefaultUtil isLogin]) {
        BaseTabBarController *baseTab = [[BaseTabBarController alloc]init];
        self.window.rootViewController = baseTab;
        [HTUtils netLoadNotification];
    }else{
        HTLoginVC *login = [[HTLoginVC alloc]init];
        BaseNavigationController *nav  = [[BaseNavigationController alloc]initWithRootViewController:login];
        self.window.rootViewController = nav;
    }
    return YES;
}
- (void)configUmPush:(NSDictionary *)launchOptions{
    [UMessage startWithAppkey:kUmeKey launchOptions:launchOptions httpsEnable:YES];
    [UMessage openDebugMode:YES];
    //友盟推送添加一个开屏通知
  //  [UMessage addLaunchMessageWithWindow:self.window finishViewController:self.navController];
    //注册通知
    [UMessage registerForRemoteNotifications];
    //调试打印
    [UMessage setLogEnabled:YES];
    //iOS10必须加下面这段代码。
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            
        } else {
            //点击不允许
        }
    }];
#endif
    
    [UMessage setAutoAlert:NO];
    //当app未运行状态的时候，接收到通知
    NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    DBLog(@"APP未运行状态时候的通知：userInfo:%@",userInfo);
    [self configNotificationAlert:userInfo];
    
}
//配置友盟统计
- (void)configUmClik{
    UMConfigInstance.appKey = kUmeKey;
    UMConfigInstance.channelId = @"App Store";
    UMConfigInstance.bCrashReportEnabled = YES;
    /** 设置是否对日志信息进行加密, 默认NO(不加密). */
    [MobClick setEncryptEnabled:YES];
    //输出log日志
    //     [MobClick setLogEnabled:YES];
    //发送错误报告
    [MobClick setCrashReportEnabled:YES];
    //发送版本号
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick startWithConfigure:UMConfigInstance];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark --- 友盟推送
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    //1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    // [UMessage registerDeviceToken:deviceToken];
    [HTMUserDefaultUtil saveDeviceToken:deviceToken];
    DBLog(@"deviceToken:%@",deviceToken);
    
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
    DBLog(@"友盟推送注册失败didFailToRegisterForRemoteNotificationsWithError：error%@",[error description]);
    
}
//ios10以下
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
   // self.userInfo = userInfo;
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"UMPuserInfoNotification"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoNotification" object:self userInfo:@{@"userinfo":[NSString stringWithFormat:@"%@",userInfo]}];
    DBLog(@"iOS10以下：接收到消息：%@",userInfo);
     [self configNotificationAlert:userInfo];
}
//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [UMessage setAutoAlert:NO];
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"UMPuserInfoNotification"];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    DBLog(@"iOS10以上：前台接收到消息：%@",userInfo);
     [self configNotificationAlert:userInfo];
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge);
    
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"UMPuserInfoNotification"];
        
    }else{
        //应用处于后台时的本地推送接受
    }
     DBLog(@"iOS10以上：后台接收到消息：%@",userInfo);
    [self configNotificationAlert:userInfo];
}
- (void)configNotificationAlert:(NSDictionary *)userInfo{
    HTNotificationResultModel *model =  [HTNotificationResultModel mj_objectWithKeyValues:userInfo[@"key1"]];
    if ([model.type isEqualToString:@"3"]) {
        [UIAlertController alertStyleShowInController:self.window.rootViewController title:@"温馨提示" message:model.message alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
            [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        } completion:nil];
    }
}

#pragma mark --- 版本更新
- (void)newVersion{
    [HTHttpRequestManager checkNewVersionSuccess:^(id  _Nullable responseObject) {
        DBLog(@"检查新版本：%@",responseObject);
        if (responseObject){
            //当前版本号
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            
            //是否强制更新字符
            NSString *force = [NSString stringWithFormat:@"%@",responseObject[@"force"]];
            
            //后台获取的版本号
            NSString *newVersion = [NSString stringWithFormat:@"%@",responseObject[@"iosV"]];
            //字符加V
            NSString *versionStr = [NSString stringWithFormat:@"V%@",newVersion];
            
            if (![appCurVersion isEqualToString:newVersion]) {
                //字符串不一样的时候
                if ([appCurVersion floatValue] > [newVersion floatValue]) {
                    //1.2.0 1.1.0 -> 1.2 1.1 不需要更新
                    return;
                }
                NSString *app  = [appCurVersion substringFromIndex:appCurVersion.length - 1];
                NSString *new  = [newVersion substringFromIndex:newVersion.length - 1];
                if ([appCurVersion floatValue] == [newVersion floatValue] && [app integerValue] >= [new integerValue]) {
                    //1.2.1  -> 1.2.0 不需要更新
                    return;
                }
                
                if ([force isEqualToString:@"1"]) {
                    //需要强制更新
                    NSString *descStr = [NSString stringWithFormat:@"%@",responseObject[@"desc"]];
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:versionStr message:descStr delegate:self cancelButtonTitle:nil otherButtonTitles:@"更新", nil];
                    
                    alertView.tag = 0;
                    [alertView show];
                    
                }else {
                    //不需要强制更新
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:versionStr message:@"新功能上线了" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                    alertView.tag = 1;
                    [alertView show];
                    
                }
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
}
//alertView代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 0 && buttonIndex == 0) {
        //强制更新
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/us/app/%E6%BB%A1%E8%BD%BD%E8%B4%A7%E8%BF%90%E8%B4%A7%E4%B8%BB/id1316321414?mt=8"]];
        
    }else if (alertView.tag == 1 && buttonIndex == 1){
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/us/app/%E6%BB%A1%E8%BD%BD%E8%B4%A7%E8%BF%90%E8%B4%A7%E4%B8%BB/id1316321414?mt=8"]];
    }
}

@end
